<?php

namespace App\V3\V3_2_7\Services;

use App\V3\V3_2_7\Models\AdminAddendumModel;
use App\V3\V3_2_7\Models\VipOrderModel;
use App\V3\V3_2_7\Models\VipSettingModel;
use  App\V3\V3_2_7\Models\AdminModel;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\V3\V3_2_7\Models\BuyStorageSpaceModel;
use App\V3\V3_2_7\Models\StorageSpaceOrderModel;
use App\Services\CommonService;
use \App\Services\MessageService;


class OrderService
{
    public static function generateSn()
    {
        $date = Carbon::now('Asia/Shanghai');
        $rnd = rand(100000, 999999);
        return $date->format('YmdHisu') . $rnd;
    }

    public static function ssGenerateSn()
    {
        $date = Carbon::now('Asia/Shanghai');
        $rnd = rand(100000, 999999);
        return 'KJ' . $date->format('YmdHisu') . $rnd;
    }

    public static function getWechatConfig()
    {
        return [
            'app_id' => config('app.miniapp_id'),
            'mch_id' => config('app.wechat_mch_id'),
            'key' => config('app.wechat_key'),
            'notify_url' => config('app.wechat_notify_url') . 'wechat_order_notify',
            //'sanbox' => true //沙箱模式打开或关闭
        ];
    }

    public static function getAPPWechatConfig()
    {
        return [
            'app_id' => config('app.appapp_id'),
            'mch_id' => config('app.wechat_mch_id'),
            'key' => config('app.wechat_key'),
            'notify_url' => config('app.wechat_notify_url') . 'wechat_order_notify',
            //'sanbox' => true //沙箱模式打开或关闭
        ];
    }

    public static function getVipSetting($id)
    {
        return VipSettingModel::select('open_vip_cost')
            ->where([
                'id' => $id,
            ])->first();
    }

    public static function payByWechat($mainId, $order_sn, $data)
    {
        if (strpos($order_sn, 'KJ') !== false) {
            //购买存储空间
            $order = StorageSpaceOrderModel::select('type', 'price')->where('order_sn', $order_sn)->first();
        } else {
            //VIP充值
            $order = VipOrderModel::select('*')->where([
                'order_sn' => $order_sn
            ])->first();
        }
        if (empty($order)) {
            return ['code' => 1, 'msg' => '订单创建失败', 'data' => ''];
        }

        switch ($order['type']) {
            case 1:
                $body = 'VIP充值';
                break;
            case 2:
                $body = '购买存储空间';

                break;
            default:
                return ['code' => 1, 'msg' => '订单错误', 'data' => ''];
        }

        $total_fee = $order['price'] * 100;

        //获取openid 如果传code 请求微信接口  不传 查询数据库
        if (!empty($data['code']) && $data['pay_type'] != 2) {
            $wxinfo = json_decode(LoginService::getOpenId($data['code']), true);
            $open_id = $wxinfo['openid'];
        } else {
            $admin = AdminModel::where('id', $mainId)->first();
            $open_id = $admin['openid'];
        }
        if ($data['pay_type'] == 2) {
            $payment = Factory::payment(self::getAPPWechatConfig());
        } else {
            $payment = Factory::payment(self::getWechatConfig());
        }

        $jssdk = $payment->jssdk;

        switch ($data['pay_type']) {
            case 1:
                //小程序
                $res = $payment->order->unify([
                    'app_id' => config('app.wepay_mini_app_id'),
                    'body' => $body,
                    'out_trade_no' => $order_sn,
                    'total_fee' => $total_fee,
                    'trade_type' => 'JSAPI',
                    'openid' => $open_id,
                    'notify_url' => config('app.wechat_notify_url') . 'wechat_order_notify',
                ]);
                break;
            case 2:
                //app
                $res = $payment->order->unify([
                    'app_id' => config('app.app_app_id'),
                    'body' => $body,
                    'out_trade_no' => $order_sn,
                    'total_fee' => $total_fee,
                    'trade_type' => 'APP',
                    /* 'openid' => $open_id, */
                    'notify_url' => config('app.wechat_notify_url') . 'wechat_order_notify',
                ]);
                break;
            default:
                $res = $payment->order->unify([
                    'app_id' => config('app.wechat_app_id'),
                    'body' => $body,
                    'out_trade_no' => $order_sn,
                    'total_fee' => $total_fee,
                    'trade_type' => 'JSAPI',
                    'openid' => $open_id,
                    'notify_url' => config('app.wechat_notify_url') . 'wechat_order_notify',
                ]);
        }

        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'SUCCESS') {
            $prepay_id = $res['prepay_id'];

            switch ($data['pay_type']) {
                case 1:
                    //小程序
                    $config = $jssdk->sdkConfig($prepay_id);
                    #$config = $jssdk->bridgeConfig($prepay_id); //json形式
                    break;
                case 2:
                    //app
                    $config = $jssdk->appConfig($prepay_id);
                    break;
                default:
                    $config = $jssdk->sdkConfig($prepay_id);
            }
            return ['code' => 0, 'msg' => '创建订单成功', 'data' => $config];

        }


        if ($res['return_code'] == 'SUCCESS' && $res['result_code'] == 'FAIL') {

            return ['code' => 0, 'msg' => '微信支付失败', 'data' => $res['err_code_des']];

        }

        if ($res['return_code'] == 'FAIL' && array_key_exists('return_msg', $res)) {

            return ['code' => 0, 'msg' => '微信支付失败', 'data' => $res['err_code_des']];
        }

    }


    public static function createOrder($mainId, $data)
    {
        if ($data['type'] == 2) {
            //创建购买存储空间的订单号
            $order_sn = self::ssGenerateSn();
        } else {
//            if(empty($data['sel_type']) || in_array(intval($data['sel_type']),[1,2,3,4,5])){
//                return ['code'=>1,'msg'=>'请选择购买VIP会员类型！','data'=>''];
//            }
//            if(empty($data['pay_money'])){
//                return ['code'=>1,'msg'=>'请选择购买VIP会员的金额！','data'=>''];
//            }
            //创建购买VIP的订单号
            $order_sn = self::generateSn();
        }

        $res = '';

        switch ($data['type']) {
            case 1:
                self::createVipOrder($order_sn, $mainId, $data);
                break;
            case 2:
                //购买存储空间
                self::createStorageSpaceOrder($order_sn, $mainId, $data);
                break;
            default:
                self::createVipOrder($order_sn, $mainId, $data);
        }

        //微信支付
        if (in_array($data['pay_type'], [1, 2])) {
            $res = self::payByWechat($mainId, $order_sn, $data);
        }

        return $res;
    }

    public static function handCreateOrder($mainId, $data)
    {
        if ($data['type'] == 2) {
            //创建购买存储空间的订单号
            $order_sn = self::ssGenerateSn();
        } else {
//            if(empty($data['sel_type']) || in_array(intval($data['sel_type']),[1,2,3,4,5])){
//                return ['code'=>1,'msg'=>'请选择购买VIP会员类型！','data'=>''];
//            }
//            if(empty($data['pay_money'])){
//                return ['code'=>1,'msg'=>'请选择购买VIP会员的金额！','data'=>''];
//            }
            //创建购买VIP的订单号
            $order_sn = self::generateSn();
        }

        $res = '';

        switch ($data['type']) {
            case 1:
                $res = self::handCreateVipOrder($order_sn, $mainId, $data);
                break;
            case 2:
                //购买存储空间
                $res = self::handCreateStorageSpaceOrder($order_sn, $mainId, $data);
                break;
            default:
                $res = self::handCreateVipOrder($order_sn, $mainId, $data);
        }

        return $res;
    }

    //创建VIP订单
    public static function createVipOrder($order_sn, $mainId, $data)
    {
        $setting_info = VipSettingModel::select('*')
            ->where('is_vip', 1)
            ->orderBy('id', 'desc')->first();

        //判断用户是否首充
        $addendum_data = AdminAddendumModel::select('*')->where(['main_id' => $mainId])->first()->toArray();

        $price = 0;
        if (empty($addendum_data['is_first_charge'])) {
            //首充
            $price = $setting_info['first_charge_price'];
        } else {
            //非首充
            $price = $setting_info['open_vip_cost'];
        }


        $data['pay_money'] = $data['pay_money'] ?? $price;
        VipOrderModel::updateOrCreate([
            'order_sn' => $order_sn,
        ], [
            'order_sn' => $order_sn,
            'main_id' => $mainId,
            'price' => $data['pay_money'],
            'type' => $data['type'],
            'sel_type' => $data['sel_type'] ?? 0,//0未选择，1天，2、月，3季度、4一年，5永久
            'album_amount' => $setting_info['album_amount'],
            'album_page_amount' => $setting_info['album_page_amount'],
            'empty_bill_amount' => $setting_info['empty_bill_amount'],
            'special_seal' => $setting_info['special_seal'],
            'one_key_album_times' => $setting_info['one_key_album_times'],
            'express_check_times' => $setting_info['express_check_times'],
            'account_storage' => $setting_info['account_storage'],
            'clear_watermark_or_not	' => $setting_info['clear_watermark_or_not'],
            'sub_account_number' => $setting_info['sub_account_number'],
        ]);
        $logData = '开通VIP，费用为：' . $data['pay_money'] . '元！';
        CommonService::operateResult($data['user_id'], $data['logTime'], $data, $logData);
    }

    //购买存储空间
    public static function createStorageSpaceOrder($order_sn, $mainId, $data)

    {
        $info = BuyStorageSpaceModel::find($data['space_id']);

        StorageSpaceOrderModel::updateOrCreate([
            'order_sn' => $order_sn,
        ], [
            'order_sn' => $order_sn,
            'main_id' => $mainId,
            'price' => $info['price'],
            'buy_storage_space' => $info['set_space'],
            'pay_type' => $data['pay_type'],
        ]);

        $logData = '存储空间' . $info['set_space'] . 'MB，费用为：' . $info['price'] . '元。';
        CommonService::operateResult($data['user_id'], $data['logTime'], $data, $logData);
    }

    public static function handCreateVipOrder($order_sn, $mainId, $data)
    {
        $setting_info = VipSettingModel::select('*')
            ->where('is_vip', 1)
            ->orderBy('id', 'desc')->first();

        //判断用户是否首充
        $addendum_data = AdminAddendumModel::select('*')->where(['main_id' => $mainId])->first()->toArray();

        $price = 0;
        if (empty($addendum_data['is_first_charge'])) {
            //首充
            $price = $setting_info['first_charge_price'];
        } else {
            //非首充
            $price = $setting_info['open_vip_cost'];
        }

        $t = time();
        $data['pay_money'] = $data['pay_money'] ?? $price;
        DB::beginTransaction();
        try {
            VipOrderModel::updateOrCreate([
                'order_sn' => $order_sn,
            ], [
                'order_sn' => $order_sn,
                'main_id' => $mainId,
                'price' => $data['pay_money'],
                'type' => $data['type'],
                'sel_type' => $data['sel_type'] ?? 0,//0未选择，1天，2、月，3季度、4一年，5永久
                'album_amount' => $setting_info['album_amount'],
                'album_page_amount' => $setting_info['album_page_amount'],
                'empty_bill_amount' => $setting_info['empty_bill_amount'],
                'special_seal' => $setting_info['special_seal'],
                'one_key_album_times' => $setting_info['one_key_album_times'],
                'express_check_times' => $setting_info['express_check_times'],
                'account_storage' => $setting_info['account_storage'],
                'clear_watermark_or_not	' => $setting_info['clear_watermark_or_not'],
                'sub_account_number' => $setting_info['sub_account_number'],
                'status' => 1,
                'pay_time' => $t,
                'out_order_sn' => 'SD' . date('YmdHis') . rand(1000, 9999)
            ]);
            self::updateVipAddendum($mainId, [
                'sel_type' => $data['sel_type'],
                'pay_time' => $t,
                'price' => $data['pay_money'],
            ]);
            $logData = '开通VIP，费用为：' . $data['pay_money'] . '元！';
            CommonService::operateResult($data['user_id'], $data['logTime'], $data, $logData);
            DB::commit();
            return ['code' => 0, 'msg' => '手动充值VIP成功', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('手动充值VIP失败：' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => '充值VIP失败', 'data' => ''];
        }
    }

    //购买存储空间
    public static function handCreateStorageSpaceOrder($order_sn, $mainId, $data): array
    {
        $info = BuyStorageSpaceModel::find($data['space_id']);
        DB::beginTransaction();
        try {
            StorageSpaceOrderModel::updateOrCreate([
                'order_sn' => $order_sn,
            ], [
                'order_sn' => $order_sn,
                'main_id' => $mainId,
                'price' => $info['price'],
                'buy_storage_space' => $info['set_space'],
                'pay_type' => $data['pay_type'],
                'status' => 1
            ]);
            $logData = '存储空间' . $info['set_space'] . 'MB，费用为：' . $info['price'] . '元。';
            CommonService::operateResult($data['user_id'], $data['logTime'], $data, $logData);
            $order = [];
            $order['order_sn'] = 'SDKJ' . date('YmdHis') . rand(1000, 9999); // 回调订单号
            $order['out_order_sn'] = 'SDKJ' . date('YmdHis') . rand(1000, 9999); // 回调流水号
            $order['pay_time'] = time();
            $ss_time = 365 * 24 * 3600;
            $storage_end_date = 0;
            $addendum_data = AdminAddendumModel::where(['main_id' => $mainId])->first();
            if (!empty(strtotime($addendum_data['storage_end_date']))) {
                $endDate = strtotime($addendum_data['storage_end_date']);
                if ($endDate > time()) {
                    //存储空间未到期，在原来的到期时间加一年。
                    $storage_end_date = $endDate + $ss_time;
                } else {
                    //第一次购买、到期购买时间重新计算
                    $storage_end_date = $order['pay_time'] + $ss_time;
                }

            } else {
                //第一次购买、到期购买时间重新计算
                $storage_end_date = $order['pay_time'] + $ss_time;
            }

            $account_storage = $addendum_data['account_storage'] + $info['set_space'] * 1024 * 1024;

            AdminAddendumModel::query()->where(['main_id' => $mainId])
                ->update([
                    'account_storage' => $account_storage,
                    'storage_end_date' => $storage_end_date
                ]);
            DB::commit();
            return ['code' => 0, 'msg' => '手动充值，存储空间成功', 'data' => ''];
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug('手动充值，存储空间失败：' . var_export($e->getMessage(), true));
            return ['code' => 1, 'msg' => '手动充值，存储空间失败', 'data' => ''];
        }

    }


    //订单回调
    public static function notifyByWeChat($fields)
    {
        $config = self::getWechatConfig();
        $payment = Factory::payment($config);
        $response = $payment->handlePaidNotify(function ($message, $fail) use ($fields) {
            //file_put_contents('./hd.txt', json_encode($message, JSON_THROW_ON_ERROR));
            //$message ='{"appid":"wx20858b923b7ae99a","bank_type":"CMB_CREDIT","cash_fee":"1000","fee_type":"CNY","is_subscribe":"N","mch_id":"1574826081","nonce_str":"66f0cccb6dd17","openid":"o41eA5Rye1q5YnBjHWkZ0XGiaM-g","out_trade_no":"KJ20240923100457548117367417","result_code":"SUCCESS","return_code":"SUCCESS","sign":"D55D4495DC28B9AA49118EC2A59D8E9C","time_end":"20240923100504","total_fee":"1000","trade_type":"JSAPI","transaction_id":"4200002345202409233302371548"}';
            //$message  = json_decode($message,true);
            if (strpos($message['out_trade_no'], 'KJ') !== false) {
                //购买存储空间
                $order = StorageSpaceOrderModel::where('order_sn', $message['out_trade_no'])
                    ->get()->toArray();
            } else {
                //VIP充值
                // 根据返回的订单号查询订单数据
                $order = VipOrderModel::where('order_sn', $message['out_trade_no'])->get()->toArray();
            }
            if (!$order) {
                $fail('订单不存在!');
            }
            $order = reset($order);

            if ($order['status'] === 1) {
                return true;
            }

            // 支付成功后的业务逻辑
            if ($message['result_code'] === 'SUCCESS') {
                Log::info('支付成功 开始操作数据库');

                $order['order_sn'] = $message['out_trade_no']; // 回调订单号
                $order['out_order_sn'] = $message['transaction_id']; // 回调流水号
                $order['pay_time'] = time();
                $order['status'] = 1;
                $mark = 'VIP';
                DB::beginTransaction();
                try {
                    Log::info('开始更新订单表');
                    if (strpos($message['out_trade_no'], 'KJ') !== false) {
                        StorageSpaceOrderModel::updateOrCreate([
                            'order_sn' => $order['order_sn'],
                        ], $order);
                        Log::info('开始更新admin_addendum表');
                        self::updateAddendum($order['main_id'], $order);
                        $mark = '存储空间';

                    } else {
                        VipOrderModel::updateOrCreate([
                            'order_sn' => $order['order_sn'],
                        ], $order);
                        #VipOrderModel::where('order_sn', $order['order_sn'])->update($order);
                        Log::info('开始更新admin_addendum表');
                        self::updateAddendum($order['main_id'], $order);
                    }
                    $userInfo = AdminModel::query()->select(
                        'username',
                        'gz_openid'
                    )->where(['id' => $order['main_id']])->first();
                    $mess = [
                        'time' => Carbon::parse()->format('Y年m月d日H:i'),
                        'phone' => $userInfo['username'],
                        'type' => $mark . '-购买',
                        'mark' => '费用(' . $order['price'] . ')元',
                        'gz_openid' => $userInfo['gz_openid']
                    ];
                    //开启VIP体验，推送开启消息
                    MessageService::buyerVipSpaceMessage($mess);
                    DB::commit();
                    Log::info('更新完成');
                    return true;
                } catch (\Exception $e) {
                    Log::info('更新失败' . var_export($e->getMessage(), true));

                    DB::rollBack();
                }
            }

            return true;
        });

        return $response;
    }

    public static function updateAddendum($main_id, $order_data)
    {
        $order_type = $order_data['type'];

        switch ($order_type) {
            case 1:
                //vip
                return self::updateVipAddendum($main_id, $order_data);
                break;
            case 2:
                //购买空间
                return self::updateSpaceOrderAddendum($main_id, $order_data);
                break;
            default:
                return false;
        }

    }

    public static function updateVipAddendum($main_id, $order_data)
    {
        $addendum_data = AdminAddendumModel::select('*')->where(['main_id' => $main_id])->first()->toArray();

        $vip_time = 365 * 24 * 3600;
        if (!empty($order_data['sel_type'])) {
            switch (intval($order_data['sel_type'])) {
                case 1://一天
                    $vip_time = 24 * 3600;
                    break;
                case 2://一个月
                    $vip_time = 30 * 24 * 3600;
                    break;
                case 3://一个季度
                    $vip_time = 90 * 24 * 3600;
                    break;
                case 4://一个年
                    $vip_time = 365 * 24 * 3600;
                    break;
                case 5://永久
                    $vip_time = 36500 * 24 * 3600;
                    break;
            }
        }
        $setting_data = VipSettingModel::select('*')
            ->where('is_vip', 1)
            ->orderBy('id', 'desc')->first();

        if (empty($addendum_data)) {
            $vip_end_date = $order_data['pay_time'] + $vip_time;
        } else {
            if (time() > strtotime($addendum_data['vip_end_date'])) {
                //会员过期
                $vip_end_date = $order_data['pay_time'] + $vip_time;
            } else {
                $vip_end_date = strtotime($addendum_data['vip_end_date']) + $vip_time;
            }
        }

        $is_vip = 1;
        $is_share_customer = empty($addendum_data) ? 0 : $addendum_data['is_share_customer'];
        $is_set_as_supplier = empty($addendum_data) ? 0 : $addendum_data['is_set_as_supplier'];
        $is_in_experience = empty($addendum_data) ? 0 : $addendum_data['is_in_experience'];
        $is_end_experience = empty($addendum_data) ? 0 : $addendum_data['is_end_experience'];
        $album_amount = empty($addendum_data) ? 0 : $setting_data['album_amount'];
        $album_page_amount = empty($addendum_data) ? 0 : $setting_data['album_page_amount'];
        $empty_bill_amount = empty($addendum_data) ? 0 : $setting_data['empty_bill_amount'];
        $special_seal = empty($addendum_data) ? 0 : $setting_data['special_seal'];
        $one_key_album_times = empty($addendum_data) ? 0 : $setting_data['one_key_album_times'];
        $express_check_times = empty($addendum_data) ? 0 : $setting_data['express_check_times'];
        $clear_watermark_or_not = empty($addendum_data) ? 0 : $setting_data['clear_watermark_or_not'];
        $file_total_size = empty($addendum_data) ? 0 : $addendum_data['file_total_size'];
        $account_storage = empty($addendum_data['account_storage']) ? $setting_data['account_storage'] : $addendum_data['account_storage'] + $setting_data['account_storage'];
        AdminAddendumModel::where('main_id', $main_id)->update([
            'main_id' => $main_id,
            'is_share_customer' => $is_share_customer,
            'is_set_as_supplier' => $is_set_as_supplier,
            'is_vip' => $is_vip,
            'vip_end_date' => $vip_end_date,
            'is_in_experience' => $is_in_experience,
            'is_end_experience' => $is_end_experience,
            'album_amount' => $album_amount,
            'album_page_amount' => $album_page_amount,
            'empty_bill_amount' => $empty_bill_amount,
            'special_seal' => $special_seal,
            'one_key_album_times' => $one_key_album_times,
            'express_check_times' => $express_check_times,
            'account_storage' => $account_storage,
            'clear_watermark_or_not' => $clear_watermark_or_not,
            'file_total_size' => $file_total_size,
            'is_first_charge' => 1,
            'sub_account_number' => -1,
            'first_charge_price' => $order_data['price'],
        ]);

        return true;
//        return AdminAddendumModel::updateOrCreate([
//            'main_id' => $main_id,
//        ],[
//
//
//        ]);
    }

    public static function updateSpaceOrderAddendum($main_id, $order_data)
    {
        $ss_time = 365 * 24 * 3600;
        $storage_end_date = 0;
        $addendum_data = AdminAddendumModel::where(['main_id' => $main_id])->first();
        if (!empty(strtotime($addendum_data['storage_end_date']))) {
            $endDate = strtotime($addendum_data['storage_end_date']);
            if ($endDate > time()) {
                //存储空间未到期，在原来的到期时间加一年。
                $storage_end_date = $endDate + $ss_time;
            } else {
                //第一次购买、到期购买时间重新计算
                $storage_end_date = $order_data['pay_time'] + $ss_time;
            }

        } else {
            //第一次购买、到期购买时间重新计算
            $storage_end_date = $order_data['pay_time'] + $ss_time;
        }

        $account_storage = $addendum_data['account_storage'] + $order_data['buy_storage_space'] * 1024 * 1024;

        return AdminAddendumModel::where(['main_id' => $main_id])->update([
            'account_storage' => $account_storage,
            'storage_end_date' => $storage_end_date
        ]);
    }

}
